/**
 * 在这里定义和用户相关的路由处理函数，供 /api/customer.js 模块进行调用
 */
const { handleQuery } = require('../db/index')
const { blob2String } = require('../utils/index')

// 接接查询字符串
function getQueryString (params) {
  const { nickname, name } = params
  const mid = []
  if (name) {
    mid.push(['user.name', `like '%${name}%'`])
  }
  if (nickname) {
    mid.push(['nickname', `like '%${nickname}%'`])
  }
  return mid.length ? 'where ' + mid.map(item => item.join(' ')).join(' and ') : ''
}
exports.getList = (req, res) => {
  const { pageSize, currentPage, prop, order } = req.body
  const str = getQueryString(req.body)
  const orderStr = (prop && order) ? ` order by ${prop} ${order === 'ascending' ? 'asc' : 'desc'} ` : ''
  const sqlStr = 'select user.name,count(score.type) as scoreNum,role,avatar,nickname,user.logtimes,user.latestlogtime from user left join score on user.name=score.name ' + str + ' group by user.name ' + orderStr + ' limit ?,? '
  const params = [(currentPage - 1) * pageSize, pageSize]
  try {
    const promiseArr = []
    let results = []
    let total = []
    const mid1 = handleQuery(sqlStr, params).then(res => {
      res.forEach((item) => {
        blob2String(item)
      })
      results = res
    })
    const mid2 = handleQuery('select count(*) as total from user ' + str, []).then(res => {
      total = res
    })
    promiseArr.push(mid1, mid2)
    Promise.all(promiseArr).then(() => {
      res.send({
        message: '查询成功',
        code: 200,
        data: results,
        total: total[0].total
      })
    })
  } catch (error) {
    res.send(error)
  }
};

